package com.wframe.project.jnd.controller;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wframe.project.jnd.entity.Promotion;
import com.wframe.project.jnd.rest.util.*;
import com.wframe.project.jnd.services.*;
import com.wframe.project.jnd.util.PromotionBuilder;
import com.wframe.project.jnd.util.PromotionBuilderFactory;
import com.wframe.project.jnd.util.TransformUtils;
import com.wframe.project.jnd.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.util.DataConvert;
import com.frame.util.DateConvert;
import com.wframe.project.former.enums.OrderStatusEnum;
import com.wframe.project.jnd.util.WebUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderService orderService;
    @Autowired
    ProductService productService;
    @Autowired
    AddressService addressService;
    @Autowired
    CouponService couponService;
    @Autowired
    PurchaseTempService tempService;
    @Autowired
    private PromotionService promotionService;

    /**
     * 获取运费模板
     *
     * @param response
     */
    @RequestMapping(value = "loadFaretemp")
    public void loadFaretemp(HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            json.putData(orderService.loadFaretemp());
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }

    }

    @RequestMapping("/cart")
    @ResponseBody
    public String showCartList(HttpSession session) throws Exception {
        String userid = WebSession.checkUserAuth(session);
        JsonReturn json = new JsonReturn();
        Map<String, Object> result = new HashMap<>();

        List<CartItem> items = orderService.findCartProducts(userid);
        int size = items.size();
        if (size > 0) {
            //购物车中有商品
            Map<String, CartItem> products = new HashMap<>();
            Map<String, Integer> tempProductStock = new HashMap<>();
            for (CartItem item : items) {
                String productid = String.valueOf(item.getProductid());

                products.put(productid, item);
                tempProductStock.put(productid, item.getAmount().intValue());
            }
            result = groupAndShow(userid, products, tempProductStock, session);
            session.setAttribute("totalPrice", result.get("totalPrice"));
        }

        result.put("count", size);
        json.putData(result);
        return json.toString();
    }

    /**
     * 进入购物车
     *
     * @param session
     */
    @RequestMapping(value = "shopcart")
    public String shopcart(HttpSession session, Model model) throws Exception {
        SessionUser loginUser = WebSession.getWbUser(session);
        if (loginUser == null) {
            return "redirect:/user/showlogin";
        }
        String userid = loginUser.getUserid();
        List<CartItem> items = orderService.findCartProducts(userid);
        int size = items.size();
        if (size > 0) {
            Map<String, CartItem> products = new HashMap<>();
            Map<String, Integer> tempProductStock = new HashMap<>();
            for (CartItem item : items) {
                String productid = String.valueOf(item.getProductid());

                products.put(productid, item);
                tempProductStock.put(productid, item.getAmount().intValue());
            }
            model.addAttribute("coupons", couponService.findOrderCoupons(tempProductStock.keySet(), userid, Promotion.Platform.PC.ordinal()));
            groupAndShow(userid, products, tempProductStock, model, session);
        }

        model.addAttribute("count", size);
        return "/website/order/shopcarts";
    }

    private void groupAndShow(String userid, Map<String, CartItem> items, Map<String, Integer> tempProductStock, Model model, HttpSession session) throws Exception {
        Map<String, Object> group = group(userid, items);
        session.setAttribute("promotions", group);

        //获取购物车中促销商品信息
        BigDecimal totalPrice = addPromotionProducts(userid, group, model, Promotion.Platform.PC.ordinal(), tempProductStock);
        session.setAttribute("tempProductStock", tempProductStock);

        if (items.size() > 0) {
            //获取购物车中无促销商品信息
            CartBean item = productService.findProducts(items, userid, Promotion.Platform.PC.ordinal());
            totalPrice = totalPrice.add(item.getTotalPrice());
            model.addAttribute("list", item.getProducts());
        }

        session.setAttribute("totalPrice", totalPrice);
        model.addAttribute("totalPrice", totalPrice);
    }

    private Map<String, Object> group(String userid, Map<String, CartItem> items) {
        Map<String, Object> tmpGroup = new HashMap<>();
        List<JdataBean> promotions = promotionService.findAll(userid, items.keySet(), Promotion.Platform.PC.ordinal());
        for (JdataBean promotion : promotions) {
            String type = promotion.getString("type");
            String productid = promotion.getString("productid");

            if ("COMMON".equalsIgnoreCase(type)) {
                continue;
            }

            if ("COMPLEX".equalsIgnoreCase(type)) {
                List<CartItem> products = (List<CartItem>) tmpGroup.get(type);
                if (products == null) {
                    products = new ArrayList<>();
                }
                products.add(items.get(productid));
                tmpGroup.put(type, products);
            } else {
                Map<String, List<CartItem>> groupItems = (Map<String, List<CartItem>>) tmpGroup.get(type);
                if (groupItems == null) {
                    groupItems = new LinkedHashMap<>();
                }

                String promotionId = promotion.getString("id");
                List<CartItem> products = groupItems.get(promotionId);
                if (Objects.isNull(products)) {
                    products = new ArrayList<>();
                }

                products.add(items.get(productid));
                groupItems.put(promotionId, products);
                tmpGroup.put(type, groupItems);
            }
            //移除促销商品
            items.remove(productid);
        }
        return tmpGroup;
    }

   /* private void groupAndShow(String userid, List<CartItem> items, HttpSession session, Model model) throws Exception {
        Map<String, Integer> tempProductStock = new HashMap<>();
        //商品分组
        Map<String, Map<String, List<CartItem>>> group = group(userid, items, tempProductStock);
        session.setAttribute("promotions", group);

        //获取购物车中促销商品信息
        BigDecimal totalPrice = addPromotionProducts(userid, group, model, tempProductStock);
        session.setAttribute("tempProductStock", tempProductStock);

        if (items.size() > 0) {
            //获取购物车中无促销商品信息
            CartBean item = productService.findProducts(userid, items);
            totalPrice = totalPrice.add(item.getTotalPrice());
            model.addAttribute("list", item.getProducts());
        }

        session.setAttribute("totalPrice", totalPrice);
        model.addAttribute("totalPrice", totalPrice);
    }*/

    private BigDecimal addPromotionProducts(String userid, Map<String, Object> group, Model model, int platform, Map<String, Integer> tempProductStock) throws Exception {
        BigDecimal totalPrice = BigDecimal.ZERO;

        Set<Map.Entry<String, Object>> typeEntries = group.entrySet();
        Iterator<Map.Entry<String, Object>> typeIterator = typeEntries.iterator();
        while (typeIterator.hasNext()) {
            Map.Entry<String, Object> typeNext = typeIterator.next();
            String type = typeNext.getKey();
            PromotionBuilder builder = PromotionBuilderFactory.get(type);
            if (type.equalsIgnoreCase("COMPLEX")) {
                List<CartItem> items = (List<CartItem>) typeNext.getValue();
                CartBean item = builder.getCartProducts(userid, null, items, platform, tempProductStock);
                totalPrice = totalPrice.add(item.getTotalPrice());
                //获取满减促销、满赠促销、其他促销的商品信息
                model.addAttribute(type.toLowerCase(), item.getProducts());
            } else {
                List<CartBean> data = new ArrayList<>();
                Map<String, List<CartItem>> map = (Map<String, List<CartItem>>) typeNext.getValue();
                Set<Map.Entry<String, List<CartItem>>> promotionEntries = map.entrySet();
                Iterator<Map.Entry<String, List<CartItem>>> promotionIterator = promotionEntries.iterator();
                while (promotionIterator.hasNext()) {
                    Map.Entry<String, List<CartItem>> promotionNext = promotionIterator.next();
                    String promotionId = promotionNext.getKey();
                    List<CartItem> items = promotionNext.getValue();

                    CartBean item = builder.getCartProducts(userid, promotionId, items, platform, tempProductStock);
                    data.add(item);
                    totalPrice = totalPrice.add(item.getTotalPrice());
                }
                //获取满减促销、满赠促销、其他促销的商品信息
                model.addAttribute(type.toLowerCase(), data);
            }
        }

        return totalPrice;
    }

    /**
     * 购物车同步
     */
    @RequestMapping(value = "toggleCart")
    @ResponseBody
    public String toggleCart(String promotionType, String promotionId, double price, CartItem item, HttpSession session) throws Exception {
        if (!WebSession.checkLoginStatus(session)) {
            throw new ClientException(CodeEnum.LoginOut);
        }

        String userid = WebSession.getWbUser(session).getUserid();

        JsonReturn json = new JsonReturn();
        List<CartItem> items = new ArrayList<>();
        CartBean bean = null;
        if ("list".equalsIgnoreCase(promotionType)) {
            Map<String, CartItem> map = new HashMap<>();
            map.put(String.valueOf(item.getProductid()), item);
            bean = productService.findProducts(map, userid, Promotion.Platform.PC.ordinal());
        } else if ("complex".equalsIgnoreCase(promotionType)) {
            PromotionBuilder builder = PromotionBuilderFactory.get(promotionType.toUpperCase());
            items.add(item);
            Map<String, Integer> tempProductStock = (Map<String, Integer>) session.getAttribute("tempProductStock");
            bean = builder.getCartProducts(userid, null, items, Promotion.Platform.PC.ordinal(), tempProductStock);
        } else {
            Map<String, Object> group = (Map<String, Object>) session.getAttribute("promotions");
            Map<String, List<CartItem>> temp = (Map<String, List<CartItem>>) group.get(promotionType.toUpperCase());
            items = temp.get(promotionId);

            Map<String, Integer> tempProductStock = (Map<String, Integer>) session.getAttribute("tempProductStock");
            for (CartItem entry : items) {
                if (entry.getId() == item.getId()) {
                    entry.setCount(item.getCount());
                    entry.setCheck(item.isCheck());
                }
            }
            temp.put(promotionId, items);
            group.put(promotionType.toUpperCase(), temp);
            session.setAttribute("promotions", group);
            PromotionBuilder builder = PromotionBuilderFactory.get(promotionType.toUpperCase());
            bean = builder.getCartProducts(userid, promotionId, items, Promotion.Platform.PC.ordinal(), tempProductStock);
        }

        HashMap<String, Object> data = new HashMap<>();
        data.put("type", promotionType);
        data.put("data", bean);
        BigDecimal totalPrice = (BigDecimal) session.getAttribute("totalPrice");
        totalPrice = totalPrice.subtract(BigDecimal.valueOf(price)).add(bean.getTotalPrice());
        session.setAttribute("totalPrice", totalPrice);
        data.put("price", totalPrice);
        json.putData(data);
        return json.toString();
    }

    /**
     * 购物车同步
     */
    @RequestMapping(value = "toggleAll")
    @ResponseBody
    public String toggleAll(double price, boolean flag, HttpSession session) throws Exception {
        if (!WebSession.checkLoginStatus(session)) {
            throw new ClientException(CodeEnum.LoginOut);
        }
        JsonReturn json = new JsonReturn();

        Map<String, Object> group = (Map<String, Object>) session.getAttribute("promotions");
        Set<Map.Entry<String, Object>> entries = group.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> next = iterator.next();
            String type = next.getKey();
            if ("complex".equalsIgnoreCase(type)) {
                List<CartItem> items = (List<CartItem>) group.get(type);
                for (CartItem item : items) {
                    item.setCheck(flag);
                }
            } else {
                Map<String, List<CartItem>> tmp = (Map<String, List<CartItem>>) group.get(type);
                Set<Map.Entry<String, List<CartItem>>> entrySet = tmp.entrySet();
                Iterator<Map.Entry<String, List<CartItem>>> entryIterator = entrySet.iterator();
                while (entryIterator.hasNext()) {
                    Map.Entry<String, List<CartItem>> entry = entryIterator.next();
                    List<CartItem> items = entry.getValue();
                    for (CartItem item : items) {
                        item.setCheck(flag);
                    }
                }
            }
        }
        session.setAttribute("promotions", group);

        BigDecimal totalPrice = BigDecimal.ZERO;
        if (flag) {
            totalPrice = BigDecimal.valueOf(price);
        }
        session.setAttribute("totalPrice", totalPrice);
        json.putData(totalPrice);
        return json.toString();
    }

    /**
     * 购物车同步
     */
    @RequestMapping(value = "syncart")
    @ResponseBody
    public String syncart(String promotionType, String promotionId, double price, CartItem item, HttpSession session) throws Exception {
        if (!WebSession.checkLoginStatus(session)) {
            throw new ClientException(CodeEnum.LoginOut);
        }

        String userid = WebSession.getWbUser(session).getUserid();
        orderService.updateCartCount(userid, String.valueOf(item.getId()), item.getCount());

        List<CartItem> items = new ArrayList<>();
        CartBean bean = null;
        if ("list".equalsIgnoreCase(promotionType)) {
            Map<String, CartItem> map = new HashMap<>();
            map.put(String.valueOf(item.getProductid()), item);
            bean = productService.findProducts(map, userid, Promotion.Platform.PC.ordinal());
        } else if ("complex".equalsIgnoreCase(promotionType)) {
            PromotionBuilder builder = PromotionBuilderFactory.get(promotionType.toUpperCase());
            items.add(item);
            Map<String, Integer> tempProductStock = (Map<String, Integer>) session.getAttribute("tempProductStock");
            bean = builder.getCartProducts(userid, null, items, Promotion.Platform.PC.ordinal(), tempProductStock);
        } else {
            Map<String, Object> group = (Map<String, Object>) session.getAttribute("promotions");
            Map<String, List<CartItem>> temp = (Map<String, List<CartItem>>) group.get(promotionType.toUpperCase());
            items = temp.get(promotionId);

            Map<String, Integer> tempProductStock = (Map<String, Integer>) session.getAttribute("tempProductStock");
            for (CartItem entry : items) {
                tempProductStock.put(String.valueOf(entry.getProductid()), entry.getAmount().intValue());
                if (entry.getId() == item.getId()) {
                    entry.setCount(item.getCount());
                    entry.setCheck(item.isCheck());
                }
            }
            temp.put(promotionId, items);
            group.put(promotionType.toUpperCase(), temp);
            session.setAttribute("promotions", group);
            PromotionBuilder builder = PromotionBuilderFactory.get(promotionType.toUpperCase());
            bean = builder.getCartProducts(userid, promotionId, items, Promotion.Platform.PC.ordinal(), tempProductStock);
        }

        JsonReturn json = new JsonReturn();
        HashMap<String, Object> data = new HashMap<>();
        data.put("type", promotionType);
        data.put("data", bean);
        BigDecimal totalPrice = (BigDecimal) session.getAttribute("totalPrice");
        if (item.isCheck()) {
            totalPrice = totalPrice.subtract(BigDecimal.valueOf(price));
        }
        totalPrice = totalPrice.add(bean.getTotalPrice());
        session.setAttribute("totalPrice", totalPrice);
        data.put("price", totalPrice);
        json.putData(data);
        return json.toString();
    }

    /**
     * 购物车商品生成订单
     */
    @RequestMapping(value = "generateorder")
    @ResponseBody
    public String generateorder(@RequestBody List<CartItem> items, HttpSession session) throws Exception {
        String userid = WebSession.getUserId(session);
        JsonReturn json = new JsonReturn();
        Map<Integer, CartItem> itemMap = new HashMap<>();

        int size = items.size();
        Integer[] ids = new Integer[size];
        for (int i = 0; i < size; i++) {
            CartItem item = items.get(i);
            if (item.getCount() < 0) {
                //商品购买数量为负数
                throw new ClientException(CodeEnum.PURCHASE_QUANTITY_ERROR);
            }

            ids[i] = item.getProductid();
        }

        items = orderService.findCartProducts(userid, ids);
        size = items.size();
        String[] cartIds = new String[size];
        for (int i = 0; i < size; i++) {
            CartItem item = items.get(i);
            itemMap.put(item.getProductid(), item);
            cartIds[i] = String.valueOf(item.getId());
        }

        //下架、价格、库存、控销校验
        Map<String, List<Map>> checkResult = orderService.checkProducts(userid, itemMap, Promotion.Platform.PC.ordinal());
        Set<Map.Entry<String, List<Map>>> entries = checkResult.entrySet();
        Iterator<Map.Entry<String, List<Map>>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, List<Map>> next = iterator.next();
            List<Map> products = next.getValue();
            if (!products.isEmpty()) {
                return json.toErrorString(this.getClass(), new ClientException(JSON.toJSONString(products), next.getKey()));
            }
        }

        //分组并处理商品
        CartBean bean = groupAndProcess(userid, itemMap, session);
        //生成订单
        String orderCode = orderService.generateOrder(userid, cartIds, bean);

        Map map = new HashMap();
        map.put("isInventoryChange", bean.isInventoryChange());
        map.put("orderCode", orderCode);
        json.putData(map);
        return json.toString();
    }

    private CartBean groupAndProcess(String userid, Map<Integer, CartItem> itemMap, HttpSession session) throws Exception {
        Map<String, Integer> tempProductStock = new HashMap<>();
        Map<Integer, JdataBean> productMap = new HashMap<>();

        List<JdataBean> products = productService.findProducts(userid, itemMap, Promotion.Platform.PC.ordinal());
        for (JdataBean product : products) {
            Integer productid = product.getInt("productid");
            CartItem item = itemMap.get(productid);

            product.put("count", item.getCount());
            productMap.put(productid, product);
            tempProductStock.put(String.valueOf(productid), item.getAmount().intValue());
        }
        //商品分组
        Map<String, Map<String, List<JdataBean>>> group = group(productMap, userid);
        //商品处理
        return process(group, tempProductStock, session);
    }

    private CartBean process(Map<String, Map<String, List<JdataBean>>> group, Map<String, Integer> tempProductStock, HttpSession session) throws Exception {
        CartBean result = new CartBean();
        BigDecimal totalPrice = BigDecimal.ZERO;
        BigDecimal restMoney = BigDecimal.ZERO;
        BigDecimal discountMoney = BigDecimal.ZERO;
        List<CartProductVO> products = new ArrayList<>();

        Set<Map.Entry<String, Map<String, List<JdataBean>>>> te = group.entrySet();
        Iterator<Map.Entry<String, Map<String, List<JdataBean>>>> ti = te.iterator();
        while (ti.hasNext()) {
            Map.Entry<String, Map<String, List<JdataBean>>> tn = ti.next();
            PromotionBuilder builder = PromotionBuilderFactory.get(tn.getKey());

            Map<String, List<JdataBean>> promotions = tn.getValue();
            Set<Map.Entry<String, List<JdataBean>>> entries = promotions.entrySet();
            Iterator<Map.Entry<String, List<JdataBean>>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                CartBean item = builder.process(iterator.next(), tempProductStock);
                //赠品数量发生变动
                Map<String, Integer> sessionProductStock = (Map<String, Integer>) session.getAttribute("tempProductStock");
                if (sessionProductStock != null && builder.checkInventoryChange(sessionProductStock, item)) {
                    result.setInventoryChange(true);
                }
                //订单项总价格
                BigDecimal unitTotalPrice = item.getTotalPrice();
                if (unitTotalPrice.compareTo(BigDecimal.ZERO) <= 0) {
                    //订单项总价格为负数或0
                    throw new ClientException(CodeEnum.Err);
                }
                totalPrice = totalPrice.add(unitTotalPrice);
                if (item.isAvailable()) {
                    //满减分摊后剩余价格
                    restMoney = restMoney.add(item.getRestMoney());
                    //满减优惠金额
                    discountMoney = discountMoney.add(item.getDiscountMoney());
                }
                products.addAll(item.getProducts());
            }
        }

        result.setTotalPrice(totalPrice);
        result.setDiscountMoney(discountMoney);
        result.setRestMoney(restMoney);
        result.setProducts(products);
        return result;
    }

    private Map<String, Map<String, List<JdataBean>>> group(Map<Integer, JdataBean> products, String userid) {
        Map<String, Map<String, List<JdataBean>>> tmpGroup = new HashMap<>();

        List<JdataBean> promotions = promotionService.findSpecificPromotions(userid, products.keySet(), Promotion.Platform.PC.ordinal());
        for (JdataBean promotion : promotions) {
            String type = promotion.getString("type");
            Integer productid = promotion.getInt("id");
            Map<String, List<JdataBean>> groupItems = tmpGroup.get(type);
            if (groupItems == null) {
                groupItems = new HashMap<>();
            }

            String promotionId = promotion.getString("promotionid");
            List<JdataBean> items = groupItems.get(promotionId);
            if (items == null) {
                items = new ArrayList<>();
            }

            items.add(products.get(productid));
            groupItems.put(promotionId, items);
            tmpGroup.put(type, groupItems);
            //移除满减、满赠促销商品
            products.remove(productid);
        }

        if (products.size() > 0) {
            Map<String, List<JdataBean>> groupItems = new HashMap<>();
            groupItems.put(null, new ArrayList<>(products.values()));
            tmpGroup.put("COMPLEX", groupItems);
        }
        return tmpGroup;
    }

   /* private CartBean processPromotion(String userId, Map<String, Map<String, List<CartItem>>> tmpGroup, Map<String, Integer> tempProductStock, HttpSession session) throws Exception {
        CartBean result = new CartBean();
        List<Product> errors = new ArrayList<>();
        List<Product> errorsMsg = new ArrayList<>();
        List<Map> errs = new ArrayList<>();
        BigDecimal totalPrice = BigDecimal.ZERO;
        BigDecimal discountMoney = BigDecimal.ZERO;
        BigDecimal restMoney = BigDecimal.ZERO;
        List<CartProductVO> products = new ArrayList<>();

        Set<Map.Entry<String, Map<String, List<CartItem>>>> typeEntries = tmpGroup.entrySet();
        Iterator<Map.Entry<String, Map<String, List<CartItem>>>> typeIterator = typeEntries.iterator();
        while (typeIterator.hasNext()) {
            Map.Entry<String, Map<String, List<CartItem>>> typeNext = typeIterator.next();
            String type = typeNext.getKey();
            PromotionBuilder builder = PromotionBuilderFactory.get(type);

            Map<String, List<CartItem>> map = typeNext.getValue();
            Set<Map.Entry<String, List<CartItem>>> promotionEntries = map.entrySet();
            Iterator<Map.Entry<String, List<CartItem>>> promotionIterator = promotionEntries.iterator();
            while (promotionIterator.hasNext()) {
                Map.Entry<String, List<CartItem>> promotionNext = promotionIterator.next();
                String promotionId = promotionNext.getKey();
                List<CartItem> items = promotionNext.getValue();
                //校验商品下架
                errs.addAll(builder.checkStatus(items));
                //校验商品库存
                errors.addAll(builder.checkInventory(userId, promotionId, items));
                errorsMsg.addAll(builder.checkLimitCount(userId, promotionId, items, Promotion.Platform.PC.ordinal()));
                CartBean item = builder.getData(userId, promotionId, items, Promotion.Platform.PC.ordinal(), tempProductStock);
                //赠品数量发生变动
                Map<String, Integer> sessionProductStock = (Map<String, Integer>) session.getAttribute("tempProductStock");
                if (sessionProductStock != null && builder.checkInventoryChange(sessionProductStock, item)) {
                    result.setInventoryChange(true);
                }
                //校验商品价格
                builder.checkPrice(item.getProducts());
                //订单项总价格
                BigDecimal unitTotalPrice = item.getTotalPrice();
                if (unitTotalPrice.compareTo(BigDecimal.ZERO) <= 0) {
                    //订单项总价格为负数或0
                    throw new ClientException(CodeEnum.Err);
                }
                totalPrice = totalPrice.add(unitTotalPrice);
                if (item.isAvailable()) {
                    //满减分摊后剩余价格
                    restMoney = restMoney.add(item.getRestMoney());
                    //满减优惠金额
                    discountMoney = discountMoney.add(item.getDiscountMoney());
                }
                products.addAll(item.getProducts());
            }
        }
        if (errors.size() > 0) {
            throw new ClientException(JSON.toJSONString(errors), "101");
        }
        if (errorsMsg.size() > 0) {
            throw new ClientException(JSON.toJSONString(errorsMsg), "4011");
        }
        if (errs.size() > 0) {
            throw new ClientException(JSON.toJSONString(errs), "102");
        }

        result.setTotalPrice(totalPrice);
        result.setDiscountMoney(discountMoney);
        result.setRestMoney(restMoney);
        result.setProducts(products);
        return result;
    }

    private Map<String, Map<String, List<CartItem>>> group(String userid, List<CartItem> items, Map<String, Integer> tempProductStock) throws Exception {
        Map<String, Map<String, List<CartItem>>> tmpGroup = new HashMap<>();
        for (int i = items.size() - 1; i >= 0; --i) {
            String productid = String.valueOf(items.get(i).getProductid());
            tempProductStock.put(productid, items.get(i).getAmount().intValue());

            Map<String, String> promotions = promotionService.findAll(productid, userid);
            Set<Map.Entry<String, String>> entries = promotions.entrySet();
            Iterator<Map.Entry<String, String>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                String type = next.getKey();
                PromotionBuilder builder = PromotionBuilderFactory.get(type);

                String promotionId = next.getValue();
                if (builder.isAvailable(userid, promotionId)) {
                    if (type.equalsIgnoreCase(Promotion.Type.FLASH_SALE.name()) || type.equalsIgnoreCase(Promotion.Type.BUY_SEND.name())) {
                        type = "COMPLEX";
                    }
                    Map<String, List<CartItem>> groupItems = tmpGroup.get(type);
                    if (groupItems == null) {
                        groupItems = new LinkedHashMap<>();
                    }

                    List<CartItem> ids = groupItems.get(promotionId);
                    if (Objects.isNull(ids)) {
                        ids = new ArrayList<>();
                    }
                    ids.add(items.get(i));
                    groupItems.put(promotionId, ids);
                    tmpGroup.put(type, groupItems);
                    //移除促销商品
                    items.remove(i);
                    break;
                }
            }
        }
        return tmpGroup;
    }*/

    private Map<String, Object> groupAndShow(String userid, Map<String, CartItem> items, Map<String, Integer> tempProductStock, HttpSession session) throws Exception {
        //商品分组
        Map<String, Object> group = group(userid, items);
        session.setAttribute("promotions", group);
        //获取购物车中商品信息
        Map<String, Object> result = addPromotionProducts(userid, group, tempProductStock);
        session.setAttribute("tempProductStock", tempProductStock);

        BigDecimal totalPrice = (BigDecimal) result.get("totalPrice");
        if (items.size() > 0) {
            //获取购物车中无促销商品信息
            CartBean item = productService.findProducts(items, userid, Promotion.Platform.PC.ordinal());
            result.put("totalPrice", totalPrice.add(item.getTotalPrice()));
            result.put("list", item.getProducts());
        }
        return result;
    }

    private Map<String, Object> addPromotionProducts(String userid, Map<String, Object> group, Map<String, Integer> tempProductStock) throws Exception {
        Map<String, Object> result = new HashMap();
        BigDecimal totalPrice = BigDecimal.ZERO;

        Set<Map.Entry<String, Object>> typeEntries = group.entrySet();
        Iterator<Map.Entry<String, Object>> typeIterator = typeEntries.iterator();
        while (typeIterator.hasNext()) {
            Map.Entry<String, Object> typeNext = typeIterator.next();
            String type = typeNext.getKey();
            PromotionBuilder builder = PromotionBuilderFactory.get(type);
            List<CartBean> data = new ArrayList<>();
            if (type.equalsIgnoreCase("COMPLEX")) {
                List<CartItem> items = (List<CartItem>) typeNext.getValue();
                CartBean item = builder.getCartProducts(userid, null, items, Promotion.Platform.PC.ordinal(), tempProductStock);
                totalPrice = totalPrice.add(item.getTotalPrice());
                //获取满减促销、满赠促销、其他促销的商品信息
                result.put(type.toLowerCase(), item.getProducts());
            } else {
                Map<String, List<CartItem>> map = (Map<String, List<CartItem>>) typeNext.getValue();
                Set<Map.Entry<String, List<CartItem>>> promotionEntries = map.entrySet();
                Iterator<Map.Entry<String, List<CartItem>>> promotionIterator = promotionEntries.iterator();
                while (promotionIterator.hasNext()) {
                    Map.Entry<String, List<CartItem>> promotionNext = promotionIterator.next();
                    String promotionId = promotionNext.getKey();
                    List<CartItem> items = promotionNext.getValue();

                    CartBean item = builder.getCartProducts(userid, promotionId, items, Promotion.Platform.PC.ordinal(), tempProductStock);
                    data.add(item);

                    totalPrice = totalPrice.add(item.getTotalPrice());
                    //获取满减促销、满赠促销、其他促销的商品信息
                    result.put(type.toLowerCase(), data);
                }
            }
        }
        result.put("totalPrice", totalPrice);
        return result;
    }

    /**
     * 商品直接生成订单
     *
     * @param data
     * @param response
     */
    @RequestMapping(value = "generateorder2")
    public void generateorder2(String data, String type, HttpSession session, HttpServletResponse response) throws Exception {
        if ("orderbuyagain".equals(type)) {
            String userid = WebSession.getUserId(session);
            JsonReturn json = new JsonReturn();
            Map<Integer, CartItem> itemMap = new HashMap<>();

            List<CartItem> items = orderService.findOrderProducts(data);
            int size = items.size();
            for (int i = 0; i < size; i++) {
                CartItem item = items.get(i);
                int productid = item.getProductid();
                itemMap.put(productid, item);
            }

            //下架、价格、库存、控销校验
            Map<String, List<Map>> checkResult = orderService.checkProducts(userid, itemMap, Promotion.Platform.PC.ordinal());
            Set<Map.Entry<String, List<Map>>> entries = checkResult.entrySet();
            Iterator<Map.Entry<String, List<Map>>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, List<Map>> next = iterator.next();
                List<Map> products = next.getValue();
                if (!products.isEmpty()) {
                    WebUtils.responseWrite(response, json.toErrorString(this.getClass(), new ClientException(JSON.toJSONString(products), next.getKey())));
                    return;
                }
            }

            //分组并处理商品
            CartBean bean = groupAndProcess(userid, itemMap, session);
            //生成订单
            json.putData(orderService.generateOrder(userid, null, bean));
            WebUtils.responseWrite(response, json.toString());
        }
       /* JsonReturn json = new JsonReturn();
        try {
            session.removeAttribute("tempProductStock");
            if (WebSession.getWbUser(session) == null || !WebSession.checkWbUserAuth(session)) {
                throw new ClientException(CodeEnum.NoAuth);
            }
            List<PriceBeanVo> carts = new ArrayList<PriceBeanVo>();
            int amount = 0;
            if ("alloften".equals(type)) {
                //购买全部常购清单商品
                JdataBean parm = new JdataBean();
                parm.put("queryinfo", "false");
                parm.put("userid", WebSession.getWbUser(session).getUserid());
                parm.put("like", data);
                parm.put("canbuy", "true");
                List<Map> list = orderService.queryOften(parm, -1, 1).getList();
                if (list.size() == 0) {
                    throw new ClientException("没有您可购的商品");
                }
                for (Map m : list) {
                    carts.add(new PriceBeanVo(m.get("id").toString(), Integer.parseInt(m.get("buyamount").toString())));
                    amount++;
                }
            } else
        if ("orderbuyagain".equals(type)) {
            //订单再次购买
            String userid = WebSession.getWbUser(session).getUserid();
            List<CartItem> items = orderService.findOrderProducts(data);
            //商品分组
            Map<String, Integer> tempProductStock = new HashMap<>();
            Map<String, Map<String, List<CartItem>>> group = group(userid, items, tempProductStock);
            //处理促销商品
            CartBean result = processPromotion(userid, group, tempProductStock, session);

            if (items.size() > 0) {
                //处理非促销商品
                CartBean item = orderService.buyAgain(userid, items);
                result.setTotalPrice(result.getTotalPrice().add(item.getTotalPrice()));
                result.getProducts().addAll(item.getProducts());
            }

            json.putData(orderService.generateOrder(userid, null, result));
            WebUtils.responseWrite(response, json.toString());
            return;
        } else if ("panbuy".equals(type)) {
                //购买采购计划
                List<Map> list = tempService.queryPlanProduct(data, null, -1, 1).getList();
                if (list.size() == 0) {
                    throw new ClientException("没有您可购的商品");
                }
                for (Map m : list) {
                    carts.add(new PriceBeanVo(m.get("id").toString(), Integer.parseInt(m.get("buyamount").toString())));
                    amount++;
                }
            } else {
                JSONArray arrs = JSON.parseArray(data);
                if (arrs.size() == 0) {
                    throw new ClientException("请选择商品");
                }
                for (int i = 0; i < arrs.size(); i++) {
                    JdataBean pro = productService.getProductPrice(arrs.getJSONObject(i).getString("priceid"));
                    boolean can = productService.getControlsales(WebSession.getWbUser(session).getUserid(), pro.getString("productid"));//控销
                    if (can) {
                        int num = arrs.getJSONObject(i).getIntValue("num");
                        carts.add(new PriceBeanVo(arrs.getJSONObject(i).getString("priceid"), num));
                        amount += num;
                    }
                }
            }
            if (carts.size() > 0) {
                double freight = 0;//运费
                JdataBean address = addressService.getCompanyAddress(WebSession.getWbUser(session).getUserid());
                if (address != null) {
                    freight = orderService.calculateFreight(address.getString("shen"), address.getString("shi"), amount);
                }
                String orderid = orderService.generateorder2(WebSession.getWbUser(session).getUserid(), carts, freight);
                json.putData(orderid);
            } else {
                throw new ClientException("该商品不在您的可购范围");
            }
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }*/

    }

    /**
     * 订单确认页
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "orderconfirm")
    public String orderconfirm(String ordercode, HttpSession session, HttpServletRequest request, Model model) throws
            ClientException {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "redirect:/user/showlogin";
        }
        List<Map> products = orderService.queryOrderProduct(ordercode);
        JdataBean order = orderService.getOrderByCode(ordercode);
        JdataBean address = addressService.getCompanyAddress(WebSession.getWbUser(request.getSession()).getUserid());
        model.addAttribute("products", products);
        model.addAttribute("order", order.getDataMap());
        if (address != null) {
            model.addAttribute("address", address.getDataMap());
        }
        double paymoney = order.getDouble("pay_money");//支付金额
        paymoney += order.getDouble("fare_money");
        model.addAttribute("paymoney", paymoney);
        productService.queryPricegrade(WebSession.getWbUser(request.getSession()).getUserid(), products);//价格等级

        PageResult couponPr = couponService.queryCanCoupon(WebSession.getWbUser(session).getUserid(), paymoney, UserService.UserSourceEnum.PC.ordinal(), 100, 1);
        List<Map> couponList = couponPr.getList();
        Iterator<Map> couponIterator = couponList.iterator();
        while (couponIterator.hasNext()) {
            Map couponItem = couponIterator.next();
            couponItem.put("id", WebUtils.aesEncode(couponItem.get("id").toString()));//id加密
        }
        model.addAttribute("couponCanList", couponList);

        PageResult couponDisPr = couponService.queryDisCoupon(WebSession.getWbUser(session).getUserid(), paymoney, UserService.UserSourceEnum.PC.ordinal(), 100, 1);
        List<Map> couponDisList = couponDisPr.getList();
        Iterator<Map> couponDisIterator = couponDisList.iterator();
        while (couponDisIterator.hasNext()) {
            Map couponDisItem = couponDisIterator.next();
            couponDisItem.put("id", WebUtils.aesEncode(couponDisItem.get("id").toString()));//id加密
        }
        model.addAttribute("couponDisList", couponDisList);

        List<CartItem> items = orderService.findOrderItem(ordercode);

        CartProduct cartProduct = new CartProduct();

        cartProduct.setItems(items);

        model.addAttribute("items", JSON.toJSON(cartProduct));

        return "/website/order/orderconfirm";
    }

    /**
     * 提交订单
     *
     * @param ordercode
     * @param response
     * @return
     */
    @RequestMapping(value = "submitOrder")
    public void submitOrder(String ordercode, int paytype, String orderbz, int deliverstype, int isinvoice, String
            couponid, String remind, String remind_phone, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }

            JdataBean order = orderService.getOrderByCode(ordercode);
            if (!order.getString("userid").equals(WebSession.getWbUser(session).getUserid())) {
                throw new Exception("非法请求!");
            }
            if (order.getInt("status") > 0) {
                throw new ClientException("订单已经提交过了，请退出页面!");
            }
            JdataBean address = addressService.getCompanyAddress(WebSession.getWbUser(session).getUserid());
            JdataBean bean = new JdataBean();
            bean.put("id", order.getString("id"));
            bean.put("paytype", paytype);
            bean.put("bz", orderbz);
            bean.put("deliverstype", deliverstype);
            bean.put("isinvoice", isinvoice);
            bean.put("source", UserService.UserSourceEnum.PC.ordinal());
            if (address != null) {
                bean.put("receipt_user", address.getString("getuser"));
                bean.put("receipt_phone", address.getString("phone"));
                bean.put("receipt_shen", address.getString("shen"));
                bean.put("receipt_shi", address.getString("shi"));
                bean.put("receipt_qu", address.getString("qu"));
                bean.put("receipt_address", address.getString("address"));
            }
            double paymoney = order.getDouble("pay_money");//支付金额
            paymoney += order.getDouble("fare_money");
            if (StringUtils.isNotBlank(couponid)) {
                JdataBean coupon = couponService.getCoupon(WebUtils.aesDecrypt(couponid));
                if (coupon != null) {
                    //使用优惠劵
                    bean.put("yh_money", coupon.getDouble("offer_money"));
                    paymoney = DataConvert.doubleSub(paymoney, coupon.getDouble("offer_money"));
                    bean.put("couponid", WebUtils.aesDecrypt(couponid));
                }
            }
            if (paymoney < 0) paymoney = 0;
            bean.put("pay_money", paymoney);
            bean.put("remind", remind);
            bean.put("remind_phone", remind_phone);
            String paycode = orderService.submitOrder(order.getString("userid"), bean, order.getString("cartids"), order.getString("code"));
            JdataBean redata = new JdataBean();
            redata.put("paycode", paycode);
            redata.put("ordercode", ordercode);
            if (paytype == 2) {
                //货到付款
                orderService.orderOk(paycode);
                redata.put("orderok", "true");
            }
            json.putData(redata);
            session.removeAttribute("tempProductStock");
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 进入订单成功页
     *
     * @param ordercode
     */
    @RequestMapping(value = "showorderOk")
    public String showorderOk(String ordercode, Model model, HttpSession session) throws ClientException {
        if (!WebSession.checkLoginStatus(session)) {
            throw new ClientException(CodeEnum.LoginOut);
        }
        JdataBean order = orderService.getOrderByCode(ordercode);
        model.addAttribute("order", order.getDataMap());
        return "/website/order/orderOk";
    }

    /**
     * 添加到购物车
     *
     * @param amount
     * @param pid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "addToCart")
    @ResponseBody
    public String addToCart(Integer amount, String pid, HttpSession session, ModelMap map) throws Exception {
        //购买商品数量为负数或不存在
        Assert.isTrue(Objects.nonNull(amount) && amount > 0, "添加的商品数目不正确");

        String userid = WebSession.checkUserAuth(session);
        JsonReturn json = new JsonReturn();

        UrgentProduct product = productService.findCartProduct(userid, pid);
        if (Objects.isNull(product)) {
            //购买商品已下架
            map.put("url", "/product/offMsg");
            json.putData(map);
            return json.toString();
        }

        if (product.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            //商品价格小于等于0
            throw new ClientException(CodeEnum.PURCHASE_PRICE_ERROR);
        }

        if (product.isControl()) {
            //商品被控销
            throw new ClientException(CodeEnum.OUT_CONTROL_AREA);
        }

        Integer count = product.getNum();
        boolean exist = count != null;
        count = exist ? count + amount : amount;
        if (count > product.getAmount()) {
            //购买商品数量加上购物车中已有商品数量大于总库存
            throw new ClientException(CodeEnum.INVENTORY_SHORTAGE);
        }

        JdataBean promotion = promotionService.findFlashSaleByProductId(pid, userid, Promotion.Platform.PC.ordinal());
        if (Objects.nonNull(promotion)) {
            //单品促销
            if (count > promotion.getInt("amount")) {
                //单品促销库存不足
                throw new ClientException(CodeEnum.PROMOTION_INVENTORY_SHORTAGE);
            } else if (promotionService.isTimeLimit(count, userid, promotion.getString("id"))) {
                //单品促销次数限制
                throw new ClientException(CodeEnum.PROMOTION_TIME_LIMIT);
            } else if (promotion.getBigDecimal("price").compareTo(BigDecimal.ZERO) <= 0) {
                //单品促销商品价格小于等于0
                throw new ClientException(CodeEnum.PURCHASE_PRICE_ERROR);
            }
        }

        orderService.addToCart(userid, pid, pid, amount);

        map.put("exist", exist);
        json.putData(map);
        return json.toString();
    }

    @RequestMapping(value = "delCart")
    @ResponseBody
    public String delCart(@RequestParam(value = "ids[]") String[] ids, HttpSession session) throws ClientException {
        if (!WebSession.checkLoginStatus(session)) {
            throw new ClientException(CodeEnum.LoginOut);
        }
        orderService.delCart(WebSession.getUserId(session), ids);
        JsonReturn json = new JsonReturn();
        return json.toString("/order/shopcart");
    }

    /**
     * 单独订单详情页
     *
     * @param ordercode
     * @return
     */
    @RequestMapping(value = "showorderinfo")
    public String orderinfo(String ordercode, HttpSession session, Model model) throws ClientException {
        model.addAttribute("ordercode", ordercode);
        return "/website/order/showorderinfo";
    }

    /**
     * 加载订单详情信息
     *
     * @param ordercode
     * @return
     */
    @RequestMapping(value = "loadorderinfo")
    public String loadorderinfo(String ordercode, Model model) throws ClientException {
        JdataBean order = orderService.getOrderByCode(ordercode);
        List<Map> productlist = orderService.queryOrderProduct(ordercode);
        model.addAttribute("order", order.getDataMap());
        model.addAttribute("products", productlist);
        return "/website/order/orderinfo";
    }

    /**
     * 我的订单列表
     *
     * @param ordercode
     * @param productname
     * @param productcode
     * @param start
     * @param end
     * @param timetype
     * @param psize
     * @param pno
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "orderlist")
    public String orderlist(Model model, String ordercode, String productname, String queryList, String
            productcode, String start, String end, String timetype, String psize, String pno, Integer
                                    status, HttpServletRequest request) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "redirect:/user/showlogin";
        }
        ordercode = TransformUtils.trans(ordercode);
        productname = TransformUtils.trans(productname);
        productcode = TransformUtils.trans(productcode);
        start = TransformUtils.trans(start);
        end = TransformUtils.trans(end);
        timetype = TransformUtils.trans(timetype);
        String keyword = "";
        if (StringUtils.isNotBlank(queryList)) {
            queryList = queryList.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            keyword = URLDecoder.decode(queryList, "UTF-8");
        }

        int pagesize = 8;
        int pageno = 1;
        if (StringUtils.isNotBlank(psize)) pagesize = Integer.parseInt(psize);
        if (StringUtils.isNotBlank(pno)) pageno = Integer.parseInt(pno);
        JdataBean parms = new JdataBean();
        parms.put("ordercode", ordercode);
        parms.put("productname", productname);
        parms.put("productcode", productcode);
        parms.put("start", start);
        parms.put("end", end);
        parms.put("backtag", 0);
        parms.put("status", status);
        parms.put("queryList", keyword);
        parms.put("userid", WebSession.getWbUser(request.getSession()).getUserid());
        Date now = new Date();
        if (StringUtils.isBlank(start) && StringUtils.isBlank(end)) {
            if ("1".equals(timetype)) {
                parms.put("end", DateConvert.toString(now, "yyyy-MM-dd"));
                parms.put("start", DateConvert.toString(DateConvert.addMonth(now, -3), "yyyy-MM-dd"));
            } else if ("2".equals(timetype)) {
                parms.put("end", DateConvert.toString(now, "yyyy-MM-dd"));
                parms.put("start", DateConvert.toString(DateConvert.addMonth(now, -12), "yyyy-MM-dd"));
            }
        }
        PageResult pr = orderService.queryOrders(parms, pagesize, pageno);
        model.addAttribute("pagecount", pr.getPageCount());
        model.addAttribute("pagesize", pr.getPageSize());
        model.addAttribute("pageno", pr.getPageNo());
        model.addAttribute("list", pr.getList());
        model.addAttribute("pagehtml", WebUtils.toPageHtml(pr, 7));
        model.addAttribute("ordercode", ordercode);
        model.addAttribute("productname", productname);
        model.addAttribute("productcode", productcode);
        model.addAttribute("start", start);
        model.addAttribute("end", end);
        model.addAttribute("status", status);
        model.addAttribute("timetype", timetype);
        model.addAttribute("queryList", keyword);
        if ("1".equals(timetype)) {
            model.addAttribute("timetypename", "近三个月的订单");
        } else if ("2".equals(timetype)) {
            model.addAttribute("timetypename", "近一年的订单");
        } else {
            model.addAttribute("timetypename", "全部");
        }
        return "/website/order/orderList";
    }

    /**
     * 确定收货
     *
     * @param ordercode
     * @param response
     */
    @RequestMapping(value = "receiptGoods")
    public void receiptGoods(String ordercode, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }
            JdataBean order = orderService.getOrderByCode(ordercode);
            if (order.getInt("status") != OrderStatusEnum.Sended.getStatus()) {
                throw new ClientException("该订单已经被处理，请刷新！");
            }
            orderService.receiptGoods(WebSession.getWbUser(session).getUserid(), ordercode);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 进入退货申请页面
     *
     * @param ordercode
     * @return
     */
    @RequestMapping(value = "showbackwrite")
    public String showbackwrite(String ordercode, Model model) throws ClientException {
        JdataBean order = orderService.getOrderByCode(ordercode);
        List<Map> productlist = orderService.queryOrderProduct(ordercode);
        model.addAttribute("order", order.getDataMap());
        model.addAttribute("products", productlist);
        return "/website/order/backwrite";
    }

    /**
     * 退货申请
     *
     * @param ordercode
     * @param response
     * @return
     */
    @RequestMapping(value = "backorder")
    public void backorder(String ordercode, String products, String photos, String reason, String
            phone, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }
            JdataBean order = orderService.getOrderByCode(ordercode);
            JdataBean bean = new JdataBean();
            bean.put("orderid", order.getString("id"));
            bean.put("reason", reason);
            bean.put("phone", phone);
            if (StringUtils.isNotBlank(photos)) {
                bean.put("photos", photos.split(","));
            }
            JSONArray arr = JSON.parseArray(products);
            bean.put("products", arr);
            orderService.backorder(bean);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 退货订单列表
     *
     * @param ordercode
     * @param productname
     * @param start
     * @param end
     * @param psize
     * @param pno
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "backorderlist")
    public String backorderlist(Model model, String ordercode, String productname, String start, String end, String
            psize, String pno, HttpServletRequest request) throws Exception {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "redirect:/user/showlogin";
        }
        int pagesize = 10;
        int pageno = 1;
        if (StringUtils.isNotBlank(psize)) pagesize = Integer.parseInt(psize);
        if (StringUtils.isNotBlank(pno)) pageno = Integer.parseInt(pno);
        JdataBean parms = new JdataBean();
        parms.put("ordercode", ordercode);
        parms.put("productname", productname);
        parms.put("start", start);
        parms.put("end", end);
        parms.put("inbacktag", "1,2,3,4,5");
        parms.put("isbacktag", "true");
        parms.put("userid", WebSession.getWbUser(request.getSession()).getUserid());
        PageResult pr = orderService.queryOrders(parms, pagesize, pageno);
        model.addAttribute("pageno", pr.getPageNo());
        model.addAttribute("list", pr.getList());
        model.addAttribute("pagehtml", WebUtils.toPageHtml(pr, 7));
        return "/website/order/backorderlist";
    }

    /**
     * 加载退货订单详情信息
     *
     * @param orderid
     * @return
     */
    @RequestMapping(value = "backorderinfo")
    public String backorderinfo(String orderid, HttpSession session, Model model) {
        if (!WebSession.checkLoginStatus(session)) {
            return "redirect:/user/showlogin";
        }

        JdataBean order = orderService.getBackOrder(orderid);
        List<Map> productlist = orderService.queryBackOrderProduct(order.getString("id"));
        double countmoney = 0;
        for (Map product : productlist) {
            countmoney += Double.parseDouble(product.get("sumprice").toString());
        }
        order.put("countmoney", countmoney);
        model.addAttribute("order", order.getDataMap());
        model.addAttribute("products", productlist);
        return "/website/order/backorderinfo";
    }

    /**
     * 取消清单
     *
     * @param response
     */
    @RequestMapping(value = "cancelorder")
    public void cancelorder(String ordercode, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }
            orderService.cancelorder(ordercode, WebSession.getWbUser(session).getUserid());
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 取消退货订单
     *
     * @param orderid
     * @param response
     * @return
     */
    @RequestMapping(value = "cancelbackorder")
    public void cancelbackorder(String orderid, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }
            orderService.cancelbackorder(orderid, WebSession.getWbUser(session).getUserid());
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 常购清单
     *
     * @param like
     * @param pno
     * @return
     */
    @RequestMapping(value = "oftenList")
    public String oftenList(Model model, String like, String pno, HttpSession session) {
        if (!WebSession.checkLoginStatus(session)) {
            return "redirect:/user/showlogin";
        }
        int pagesize = 20;
        int pageno = 1;
        if (StringUtils.isNotBlank(pno)) {
            pageno = Integer.parseInt(pno);
        }
        JdataBean parm = new JdataBean();
        parm.put("userid", WebSession.getWbUser(session).getUserid());
        parm.put("like", like);
        PageResult pr = orderService.queryOften(parm, pagesize, pageno);
        model.addAttribute("list", pr.getList());
        model.addAttribute("pagehtml", WebUtils.toPageHtml(pr, 7));
        model.addAttribute("like", like);
        return "/website/user/oftenList";
    }

    @RequestMapping(value = "delOften")
    public void delOften(String priceid, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }
            if (!WebSession.checkWbUserAuth(session)) {
                throw new ClientException(CodeEnum.NoAuth);
            }
            orderService.delOften(WebSession.getWbUser(session).getUserid(), priceid);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 加入常购清单
     *
     * @param priceid
     * @param response
     */
    @RequestMapping(value = "addOften")
    public void addOften(String priceid, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }
            if (!WebSession.checkWbUserAuth(session)) {
                throw new ClientException(CodeEnum.NoAuth);
            }
            orderService.addOften(WebSession.getWbUser(session).getUserid(), priceid);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping(value = "updateOften")
    public void updateOften(PriceBeanVo price, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if (!WebSession.checkLoginStatus(session)) {
                throw new ClientException(CodeEnum.LoginOut);
            }
            if (!WebSession.checkWbUserAuth(session)) {
                throw new ClientException(CodeEnum.NoAuth);
            }
            orderService.updateOften(price);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    //进入历史采购
    @RequestMapping(value = "loginhislistnew")
    public String loginHislistnew(HttpServletRequest request) {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "redirect:/user/showlogin";
        }
        return "/website/order/hislistnew";
    }

    /**
     * 新历史采购
     */
    @RequestMapping(value = "hislistnew")
    public void hislistnew(String pno, int platform, HttpServletRequest request, HttpSession session, String
            timeType, HttpServletResponse response) throws Exception {
        if (!WebSession.checkLoginStatus(session)) {
            throw new ClientException(CodeEnum.LoginOut);
        }
        JsonReturn json = new JsonReturn();
        int pagesize = 20;
        int pageno = 1;
        if (StringUtils.isNotBlank(pno)) pageno = Integer.parseInt(pno);
        JdataBean parm = new JdataBean();
        parm.put("userid", WebSession.getWbUser(request.getSession()).getUserid());
        parm.put("status", OrderStatusEnum.Sended.getStatus());
        Date now = new Date();
        //PC端
        if (StringUtils.isNotBlank(timeType)) {
            if ("1".equals(timeType)) {
                parm.put("end", DateConvert.toString(now, "yyyy-MM-dd"));
                parm.put("start", DateConvert.toString(DateConvert.addMonth(now, -3), "yyyy-MM-dd"));
            } else if ("2".equals(timeType)) {
                parm.put("end", DateConvert.toString(now, "yyyy-MM-dd"));
                parm.put("start", DateConvert.toString(DateConvert.addMonth(now, -6), "yyyy-MM-dd"));
            } else if ("3".equals(timeType)) {
                parm.put("end", DateConvert.toString(now, "yyyy-MM-dd"));
                parm.put("start", DateConvert.toString(DateConvert.addMonth(now, -12), "yyyy-MM-dd"));
            }
        }
        parm.put("platform", platform);
        PageResult pr = orderService.queryOrderProduct(parm, pagesize, pageno);
        json.putData(pr);
        WebUtils.responseWrite(response, json.toString());
    }

    /**
     * 获取购物车数量
     *
     * @param response
     */
    @RequestMapping(value = "getCartNum")
    public void getCartNum(HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            int num = 0;
            if (WebSession.checkLoginStatus(session)) {
                num = orderService.statCartnum(WebSession.getWbUser(session).getUserid());
            }
            json.putData(num);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }
}
